package io.zhengsh.nio.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;

public class PipeDemo {

    public static void main(String[] args) throws IOException {
        // 1 获取管道
        Pipe pipe = Pipe.open();

        // 2 获取 sink 通道
        Pipe.SinkChannel sinkChannel = pipe.sink();

        // 3 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("ha ha!".getBytes(StandardCharsets.UTF_8));
        buffer.flip();

        // 4 写入数据
        sinkChannel.write(buffer);

        // 5 source 通道
        Pipe.SourceChannel sourceChannel = pipe.source();

        // 6 创建一个缓冲区，读取数据
        ByteBuffer buffer2 = ByteBuffer.allocate(1024);
        //buffer2.flip();
        int len = sourceChannel.read(buffer2);
        String str = new String(buffer2.array(), 0, len);
        System.out.println(str);

        // 7 关闭通道
        sinkChannel.close();
        sourceChannel.close();
    }
}
